<?php
namespace app\admin\controller;

use app\admin\library\Upload;
use cubox\Controller;
use app\admin\library\User;
use cubox\Cubox;
use cubox\Check;
use cubox\provider\Url;

class Outside extends Controller{

    public function __construct()
    {
        parent::__construct();
        session_start();
    }

    public function onLogin(){
        
        $config = $this->app->config('login');

        $nav = $this->get('nav')??'';
        
        if ($nav!=''){
            $nav = Url::base64Decode($nav,true);
        }

        $this->set('wallpaper',Upload::url($config->wallpaper));
        $this->set('nav',$nav);
        $this->set('usernameReg',User::$usernameReg);
        return $this->display();
    }

    public function onLoging(){
         
        $check = new Check('用户名');
        $check->reg(User::$usernameReg)->required();
        $username = $this->post('username');

        if(!$check->check($username)){
            Cubox::log('LOGIN USERNAME_FAIL '.$username.' '.$check->message);
            throw new \Exception($check->message);
        }

        $check = new Check('密码');
        $check->required();
        $password = $this->post('password');

        if (!$check->check($password)){
            Cubox::log('LOGIN PASSWORD_FAIL '.$username.' '.$check->message);
            throw new \Exception($check->message);
        }
        if (!$this->checkTry()){
            Cubox::log('LOGIN TRY_FAIL '.$username.' 尝试次数过多，请稍后再试');
            throw new \Exception('尝试次数过多，请稍后再试');
        }

        if ($username=='' ||  $password ==''){
            $this->addTryError();

            throw new \Exception('用户名或密码不能为空');
        }

        $user = $this->model('User');



        
        $userData = $user->where('username',$username)->getRow();

        if ($userData){
            if ($userData['password'] == User::makePassword($password)){
                
                $powerExtend = [];
                try{
                    $powerExtend = json_decode($userData['power_extend'],true);
                }catch(\Exception $e){
                    $powerExtend = array();
                }


                $group = $this->model('UserGroup');
                $groupPower = $group->power((int) $userData['group_id']);
                 
                if ($groupPower['power']!=''){
                    if ($userData['power']!=''){
                        $userData['power'].= ','.$groupPower['power'];
                    }else{
                        $userData['power'] = $groupPower['power'];
                    }
                }

                $powerExtend =  User::mergeExtend($groupPower['extend'],$powerExtend??[]);

                $userData['power_extend'] = $powerExtend;
                
                $groupData = $group->getId((int) $userData['group_id']);

                if ($groupData){
                    $userData['group_title'] = $groupData['title'];
                }else{
                    throw new \Exception('用户组不存在');
                }
                
                User::setLoginData($userData);
                $this->clearTry();
                
                $logData['user_id'] = $userData['user_id'];
                $logData['username'] =  $userData['username'];
                $logData['app'] =  'admin';
                $logData['controller'] = 'outside';
                $logData['action'] =  'loging';
                $logData['title'] =  '登录成功';
                $logData['time'] =  time();
                $logData['ip'] =  $_SERVER['REMOTE_ADDR'];
             
                $this->model('UserLog')->insert($logData);

                $re ['url']  = $this->getDirectUrl(User::getPowerExtend('admin','*','userLoginDirect'));
                $re ['user'] = User::getFrontData();

                return $re;
            }else{
                $this->addTryError();
                Cubox::log('LOGIN PASSWORD_FAIL '.$username.' 密码错误');
                throw new \Exception('密码错误');
            }
        }else{
            $this->addTryError();
            Cubox::log('LOGIN USERNAME_FAIL '.$username.' 用户名不存在');
            throw new \Exception('用户名不存在');
        }
        

    }

    private function addTryError(){
        if (isset($_SESSION['admin_login_try_count'])){
            $_SESSION['admin_login_try_count']++;
        }else{
            $_SESSION['admin_login_try_count'] = 0;
        }
       

        if (!isset($_SESSION['admin_login_try_start'])){
            $_SESSION['admin_login_try_start'] = time();
        }
    }

    private function checkTry(){
        $loginCongfig =  $this->app->config('login');
        $loginTryMax  = $loginCongfig->try_max??10;
        $loginTryTime =  ($loginCongfig->failTime??60)*60;
        
        if (isset($_SESSION['admin_login_try_start']) &&  $_SESSION['admin_login_try_start'] + $loginTryTime > time()){

            if (isset($_SESSION['admin_login_try_count']) && $_SESSION['admin_login_try_count']>=$loginTryMax){
                return false;
            }
            
        }else{
            $this->clearTry();
        }

        return true;
    }

    private function clearTry(){
        unset($_SESSION['admin_login_try_start']);
        unset($_SESSION['admin_login_try_count']);
    }

    private function getDirectUrl($userDirect=null){
        $direct = '';
        if ($userDirect!=null && $userDirect!=''){
            $direct = $userDirect;
        }else{
            $loginConfig =  $this->app->config('login');
            if ($loginConfig->loginDirect){
                $direct = $loginConfig->loginDirect;
            }
        }

        if ($direct==''){
            return  $this->app->url('index','index');
        }else{
            try{
                $url = unserialize($direct);
                return Cubox::url($url['app'],$url['controller']??'index',$url['action']??'index',$url['gets']??[]);
            }catch(\Exception $e){
                throw new \Exception('非法的跳转地址');
            }
        }
    }   
}